package com.qdlc.p2p.biz.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.annotation.Resource;

import com.qdlc.p2p.common.util.DateUtil;
import com.qdlc.p2p.dal.common.model.jpa.PageDataList;
import org.springframework.stereotype.Service;

import com.qdlc.p2p.biz.service.ReceivingInfoService;
import com.qdlc.p2p.dal.dao.ReceivingInfoDao;
import com.qdlc.p2p.dal.dto.ReceivingInfo;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.model.ReceivingInfoModel;

@Service("receivingInfoService")
public class ReceivingInfoServiceImpl implements ReceivingInfoService {

    @Resource
    private ReceivingInfoDao receivingInfoDao;

	@Override
	public void save(ReceivingInfo receivingInfo) {
		if (receivingInfo.isDefultInfo()) {//如果当前收货地址设置为默认地址，则将其他默认地址修改为非默认
			receivingInfoDao.setUnDefult(receivingInfo.getUserId());
		}
		receivingInfo.setAddTime(DateUtil.getNow());
		receivingInfoDao.save(receivingInfo);
	}

	@Override
	public List<ReceivingInfo> list(User user) {
		List<ReceivingInfo> list = receivingInfoDao.list(user.getUserId(), ReceivingInfoModel.RECEIVINGINFO_STATUS_ENABLE);
		return list;
	}

	@Override
	public int count(User user) {
		int count = receivingInfoDao.count(user.getUserId(), ReceivingInfoModel.RECEIVINGINFO_STATUS_ENABLE);
		return count;
	}

	@Override
	public ReceivingInfo find(long id) {
		ReceivingInfo info = receivingInfoDao.findById(id);
		return info;
	}

	@Override
	public void update(ReceivingInfo receivingInfo) {
		ReceivingInfo oldInfo = receivingInfoDao.findById(receivingInfo.getId());
		if(receivingInfo.isDefultInfo() && !oldInfo.isDefultInfo()){//如果当前收货地址设置为默认地址，则将其他默认地址修改为非默认
			receivingInfoDao.setUnDefult(receivingInfo.getUserId());
		}
		receivingInfoDao.update(receivingInfo);
	}

	@Override
	public void setDefultReceivingInfo(ReceivingInfo model) {
		receivingInfoDao.setUnDefult(model.getUserId());
		receivingInfoDao.setDefult(model.getId(), model.getUserId());
	}

	@Override
	public void disable(long id, long userId) {
		receivingInfoDao.disable(id, userId);
	}

	@Override
	public List<ReceivingInfoModel> ListModel(User user) {
		List<ReceivingInfo> list = receivingInfoDao.list(user.getUserId(), ReceivingInfoModel.RECEIVINGINFO_STATUS_ENABLE);
		if(list == null || list.size() == 0){
			return Collections.emptyList();
		}
		//判断是否有默认
		boolean flag = false;
		
		List<ReceivingInfoModel> modelList = new ArrayList<ReceivingInfoModel>();
		for (ReceivingInfo receiv : list) {
			ReceivingInfoModel model = ReceivingInfoModel.instance(receiv);
			if (flag) {
				model.setDefultInfo(true);
			}
			modelList.add(model);
			flag=false;
		}
		return modelList;
	}

	@Override
	public PageDataList<ReceivingInfoModel> list(ReceivingInfoModel model) {
		return receivingInfoDao.list(model);
	}
}
